class RedisSessionStore {
  constructor(store) {
    this.store = store;
  }

  async get(sid) {
    const jsonSession = await this.store.get(sid);
    if (!jsonSession) {
      return jsonSession;
    }
    try {
      return JSON.parse(jsonSession);
    } catch (e) {
      return null;
    }
  }

  async set(sid, sess, maxAge) {
    const jsonSession = JSON.stringify(sess);
    return await Promise.all([
      this.store.set(sid, jsonSession, 'PX', maxAge),
      this.store.set(createUniqueCookieKey(sess.userInfo.id), sid, 'PX', maxAge)
    ]);
  }

  async destroy(sid, { ctx }) {
    // 不清理 userId:${userId}-unique-cookie 是因为
    // 存在后登录用户登录后又立即登出的情况
    // 所以这里对 userId:${userId}-unique-cookie 处理为等待再次登录的更新或过期
    // 优化方向，可以考虑用websocket通知先登录被挤下线，而不是在先登录用户请求时再提醒
    await this.store.del(sid);
  }

  async userCookieCheck(sid, { ctx }) {
    const userCookie = await this.store.get(createUniqueCookieKey(ctx.session.userInfo.id));
    return sid === userCookie;
  }
}

function createUniqueCookieKey(userId) {
  return `userId:${userId}-unique-cookie`;
}

module.exports = RedisSessionStore;